﻿using BLL;
using DevExpress.XtraEditors;
using FastReport;
using Model;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.自定义类;
using 纺织贸易管理系统;
using 纺织贸易管理系统.设置窗体;

namespace 后整理管理系统.其他窗体
{
    public partial class 工艺二次登记 : Sunny.UI.UIForm
    {
        public List <Liuzhuancard > liuzhuancards { get; set; }
        public ScheduleDoc scheduleDoc { get; set; }
        private FormUseful useful;
        public 工艺二次登记(List<Liuzhuancard> liuzhuancards,FormUseful formUseful, ScheduleDoc doc)
        {
            InitializeComponent();
            CreateGrid.Create("流程卡查询", uiDataGridView1);
            this.liuzhuancards = liuzhuancards;
            this.scheduleDoc = doc; 
            this.useful = formUseful;

        }
        private ProofingRequirements GetProofingRequirements() 
        {
            var requirements = new ProofingRequirements()
            {
                DocNum = txtliuzhuankahao.Text,
                FrontOrBack = txtzhengfangmian.Text,
                Hydraulic = txtshuiya.Text,
                MoisturePermeability = string.Empty,
                TestStandards = txtceshibiaozhun.Text,
                Trimming = txtqiebian.Text,
                Washing = txtshuixi.Text,
                WaterproofEffect = txtfangshuixiaoguo.Text,
                Weight = txtkezhong.Text,
                Width = txtmenfu.Text,
                Sticktype = txtgunxing.Text,
                Glue = txtjiaoshui.Text,
                TPU = txtdibu.Text,
                FitPressure = txttieheyali.Text,
                RewindingPressure = txtshoujuanyali.Text,
                RewindingTension = txtshoujuanzhangli.Text,
                Temperature = txtwendu.Text,
                HandFeel = txtshougang.Text,
                BottomWeight = txtBottomWeight.Text,
                DetectionMetrics = txtDetectionmetrics.Text,
                Other = txtOther.Text,
                SeamSlippage = txtSeamSlippage.Text,
                TearStrength = txtTearStrength.Text,
                TopWeight = TxtTopWeight.Text,
                Divest = txtdivest.Text,
                Sticktype1 = txtgunxing1.Text,
                Glue1 = txtjiaoshui1.Text,
                Solvent = txtrongji.Text,
                CuringAgent = txtguhuaji.Text,
                CuringAgent1 = txtguhuaji1.Text,
                Solvent1 = txtrongji1.Text,
            };
            return requirements;
        }
        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var cards = SelectHelper.GetSelectList<Liuzhuancard>(uiDataGridView1);
            if(cards.Count()==0 )
            {
                this.ShowAskDialog("没有任何流转卡被安排生产！保存失败");
                return;
            }

            var requirements = GetProofingRequirements();
                foreach (var item in cards)
                {
                    item.ArrangementDoc = txtliuzhuankahao.Text;
                    item.ArrangementDate=dateTimePicker1.Value.ToString() ;
                    item.ArrangementMan=cmbPeichanren.Text;
                    item.IsArrangementProduced = true;
                }
                try
                {
                    Connect.dbcontext.BeginTran();
                    if (useful == FormUseful.新增) 
                    {
                        var doc = new ScheduleDoc() { DocNum = txtliuzhuankahao.Text, ScheduleDate = dateTimePicker1.Value, ScheduleMan = cmbPeichanren.Text };
                        Connect.dbcontext.Insertable(requirements).ExecuteCommand ();
                        Connect.dbcontext.Insertable (doc).ExecuteCommand ();
                        Connect.dbcontext.Updateable(cards).ExecuteCommand ();
                    }
                    else
                    {
                        this.scheduleDoc.ScheduleMan = cmbPeichanren.Text;
                        this.scheduleDoc.ScheduleDate = dateTimePicker1.Value ;
                    var oldreqiorements = Connect.dbcontext.Queryable<ProofingRequirements>().First(x => x.DocNum == txtliuzhuankahao.Text);
                    if(oldreqiorements!=null)
                    {
                        requirements.ID = oldreqiorements.ID; 
                        Connect.dbcontext.Updateable(requirements).ExecuteCommand();
                    }
                   else
                    {
                        Connect.dbcontext.Insertable(requirements).ExecuteCommand();
                    }
                        Connect.dbcontext.Updateable(this.scheduleDoc).ExecuteCommand();
                        Connect.dbcontext.Updateable<Liuzhuancard>().SetColumns(x => new Liuzhuancard() { ArrangementDate=string.Empty,ArrangementDoc=string.Empty,ArrangementMan=string.Empty,IsArrangementProduced=false}).Where(x=>x.ArrangementDoc==txtliuzhuankahao.Text ).ExecuteCommand ();
                        Connect.dbcontext.Updateable(cards).ExecuteCommand();
                    }
                    Connect.dbcontext.CommitTran();
                    this.Close();
                }
                catch (Exception ex)
                {
                    Connect.dbcontext.RollbackTran();
                    ShowMessageBox.ShowErrorBox("保存的时候发生了错误！" + ex.Message);
                }
        }

        private void txtliuzhuankahao_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter)
            {
                var liuzhuangkamingxi = liuzhuanmingxiService.Getliuzhuanmingxilst(x => x.CardNum == txtliuzhuankahao.Text );

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var liuzhuangkamingxi = liuzhuanmingxiService.Getliuzhuanmingxilst(x => x.CardNum == txtliuzhuankahao.Text);

        }

        private void 工艺二次登记_Load(object sender, EventArgs e)
        {
            if(this.useful==FormUseful.新增)
            {
                Addnew();
            }
            else
            {
                if (this.useful == FormUseful.修改)
                {
                    Edit();
                }
                else
                {
                    保存ToolStripMenuItem.Enabled = false;
                }
            }
        }
        private void Addnew()
        {
            dateTimePicker1.Value = DateTime.Now;
            txtliuzhuankahao.Text= BianhaoBLL.CreatDanhao(FirstLetter.排产单, dateTimePicker1.Value, DanjuLeiXing.排产单);
            gridControl2.DataSource=this.liuzhuancards;
            uiDataGridView1.SelectAll();
            cmbPeichanren.Text = CurrentUser.user.YHMC;
        }
        private void Edit()
        {
            txtliuzhuankahao.Text=this.scheduleDoc.DocNum;
            dateTimePicker1.Value=this.scheduleDoc.ScheduleDate;
            cmbPeichanren.Text = this.scheduleDoc.ScheduleMan;
            要求赋值();
            gridControl2.DataSource = this.liuzhuancards;
            uiDataGridView1.SelectAll();
        }
        private void 要求赋值()
        {
           var requirements = Connect.dbcontext.Queryable<ProofingRequirements>().First(x => x.DocNum == txtliuzhuankahao.Text);
            if (requirements == null)
            {
                requirements = new ProofingRequirements();
            }
            txtzhengfangmian.Text = requirements.FrontOrBack;
            txtshuiya.Text = requirements.Hydraulic;
            txtceshibiaozhun.Text = requirements.TestStandards;
            txtqiebian.Text = requirements.Trimming;
            txtshuixi.Text = requirements.Washing;
            txtfangshuixiaoguo.Text = requirements.WaterproofEffect;
            txtkezhong.Text = requirements.Weight;
            txtmenfu.Text = requirements.Width;
            txtgunxing.Text = requirements.Sticktype;
            txtjiaoshui.Text = requirements.Glue;
            txtdibu.Text = requirements.TPU;
            txtwendu.Text = requirements.Temperature;
            txttieheyali.Text = requirements.FitPressure;
            txtshoujuanyali.Text = requirements.RewindingPressure;
            txtshoujuanzhangli.Text = requirements.RewindingTension;
            TxtTopWeight.Text = requirements.TopWeight;
            txtBottomWeight.Text = requirements.BottomWeight;
            txtSeamSlippage.Text = requirements.SeamSlippage;
            txtDetectionmetrics.Text = requirements.DetectionMetrics;
            txtTearStrength.Text = requirements.TestStandards;
            txtOther.Text = requirements.Other;
            txtdivest.Text = requirements.Divest;
            txtgunxing1.Text = requirements.Sticktype1;
            txtjiaoshui1.Text = requirements.Glue1;
            txtguhuaji.Text = requirements.CuringAgent;
            txtrongji.Text = requirements.Solvent;
            txtguhuaji1.Text = requirements.CuringAgent1;
            txtrongji1.Text = requirements.Solvent1;
        }

        private void 打印编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (PrintService.CheckPrintDesignAccess())
            {
                Print(PrintModel.Design);
            }
        }
        private void  Print(PrintModel model)
        {
            var fs = new Report();
            var ds=new DataSet();
            var gongyidt = new 打印打样单后整理() { Requirements=GetProofingRequirements()}.CreateRequirementsDatatable();
            gongyidt.TableName = "生产工艺";
            ds.Tables.Add(gongyidt);
            var liuzhuandt=SelectHelper.GetSelectList<Liuzhuancard>(uiDataGridView1).ToDataTable();
            liuzhuandt.TableName = "流转卡列表";
            var dt=new DataTable("排产单号");
            dt.Columns.Add("排产单号");
            dt.Columns.Add("排产日期",typeof(DateTime ));
            dt.Columns.Add("排产人");
            var dr=dt.NewRow();
            dr["排产单号"] = txtliuzhuankahao.Text;
            dr["排产日期"] = dateTimePicker1.Value;
            dr["排产人"] = cmbPeichanren.Text ;
            dt.Rows.Add(dr);
            ds.Tables.Add(dt);
            ds.Tables.Add(liuzhuandt);
          var docs=  SelectHelper.GetSelectList<Liuzhuancard>(uiDataGridView1);
            var details = Connect.dbcontext.Queryable<danjumingxitable>().Where(x =>docs.Select(y=>y.CardNum).Distinct().ToList().Contains(x.danhao)).ToList();          
            ds.Tables.Add(details.ToDataTable());
            fs.RegisterData(ds);
            if (File.Exists(Application.StartupPath + "\\Report\\排产单.frx"))
            {
                fs.Load(Application.StartupPath + "\\Report\\排产单.frx");
            }
            else
            {
                fs.Design();
                string path = Application.StartupPath + "\\Report\\排产单.frx";
                var arr = path.Split('\\');
                ReportTableService.DeleteReportTable(x => x.reportName == arr[arr.Length - 1] && x.reportStyle == ReportService.报表);
                ReportService.LoadReport(path, new ReportTable { reportStyle = ReportService.报表, reportName = arr[arr.Length - 1] });
                return;
            }
            try
            {
                switch (model)
                {
                    case PrintModel.Design:
                        fs.Design();
                        string path = Application.StartupPath + "\\Report\\排产单.frx";
                        var arr = path.Split('\\');
                        ReportTableService.DeleteReportTable(x => x.reportName == arr[arr.Length - 1] && x.reportStyle == ReportService.报表);
                        ReportService.LoadReport(path, new ReportTable { reportStyle = ReportService.报表, reportName = arr[arr.Length - 1] });
                        break;
                    case PrintModel.Privew:
                        fs.Show();
                        break;
                    case PrintModel.Print:
                        fs.Print();
                        break;
                }
            }
            catch
            {
                fs.Design();
            }
        }

        private void 打印预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Print(PrintModel.Privew);
        }

        private void 直接打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Print(PrintModel.Print);
        }
    }
}
